<?php

class Core_Model_Tag_Keyword extends Dcmp_Model_Entity {

    public function __construct() {
        parent::__construct();
    }

    protected function getTableClass() {
        return Kd_Loader::loadClass('table_tag_keyword');
    }

    public function statRecord($keyword, $accuracy = FALSE){
        return $this->getTable()->statRecord($keyword, $accuracy);
    }

    public function searchRecordIds($keyword, $type, $accuracy = FALSE){
        return $this->getTable()->searchRecordIds($keyword, $type, $accuracy);
    }

    public function registerKeyword($word){
        $this->getTable()->insertKeyword($word);
        return $this;
    }

    public function addTagRecord(array $tags, $recordId, $recordType, $transaction = NULL) {
        Kd_Util_Array::removeEmpty($tags);
        if(is_null($recordId) || empty($recordId) || empty($tags)){
            return $this;
        }
        $transaction = is_null($transaction)? Kd_Db_Factory::getTransaction(): $transaction;
        try {
            $transaction->begin();
            $dbDriver = is_null($transaction)? NULL: $transaction->getDbDriver();
            $list = App::getModel('tag/collection_keyword')
                        ->setDbDriver($dbDriver)
                        ->filterByNames($tags)
                        ->load();        
            $names = $list->getItemPropertyValue('name');
            foreach ($tags as $name) {
                if (!in_array($name, $names)) {
                    $model = new self();
                    $model->setName($name)
                          ->save($transaction);
                    $list->append($model);
                }
            }
            $this->getTable()->insertTagRecord($list->getItemPropertyValue('id'), $recordId, $recordType, $transaction);
            $transaction->commit();
        } catch (Exception $ex) {
            $transaction->rollback();
            throw $ex;
        }
        return $this;
    }

    public function removeTagRecord($recordId, $recordType, $transaction = NULL) {
        $this->getTable()->deleteTagRecord($recordId, $recordType, $transaction);
        return $this;
    }

    protected function initializeTable($table) {
        $table->setName('{t}tag_keyword');
        $table->createColumn('id', 'integer', TRUE, TRUE);
        $table->createColumn('name', 'string');
        $table->createColumn('search_count', 'integer');
    }

}